package utils

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func Generate() error {
	targetDir, err := os.Getwd()
	if err != nil {
		return err
	}

	fmt.Println(targetDir)
	err = filepath.Walk(targetDir, func(path string, info os.FileInfo, err error) error {
		if ext := filepath.Ext(path); ext != ".proto" {
			return nil
		}

		execDir := filepath.Dir(targetDir)
		name := strings.ReplaceAll(path, execDir+string(filepath.Separator), "")
		input := []string{
			"--proto_path=.",
			"--proto_path=" + filepath.Join(os.Getenv("GOPATH"), "protobuf"),
			"--go_out=paths=source_relative:.",
			"--gin_out=paths=source_relative:.",
			name,
		}

		fmt.Println(input)

		fd := exec.Command("protoc", input...)
		fd.Stdout = os.Stdout
		fd.Stderr = os.Stderr
		fd.Dir = execDir
		if err := fd.Run(); err != nil {
			return err
		}
		fmt.Printf("proto: %s\n", name)
		return nil
	})
	if err != nil {
		return err
	}

	return nil
}
